package com.mrli.cat.weather.activity;

import android.app.Fragment;
import android.app.LoaderManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AlphabetIndexer;
import android.widget.ListView;
import android.widget.TextView;

import com.mrli.cat.weather.R;
import com.mrli.cat.weather.database.WeatherContract;
import com.mrli.cat.weather.model.City;
import com.mrli.cat.weather.service.LocationService;

public class SelectCityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
    private City mLocation;
    public static final int RESULT_OK = 0xC957;
    //定义字母排序规则
    private String mAlphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //城市列表适配器
    private CityAdapter mCityAdapter;
    //城市列表视图
    private ListView mCityList;
    private static final int CITY_LOADER = 0x5896;
    private Cursor mData;
    public static final String CITY = SelectCityFragment.class.getName() + ":city";
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TextView location = (TextView) getActivity().findViewById(R.id.current_location);
            if (intent.getAction().equals(ForecastFragment.ACTION_LOCATION_DONE)) {
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    mLocation = bundle.getParcelable(ForecastFragment.CITY_INFO);
                    location.setText(mLocation.getmCityName());
                    location.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mLocation != null) {
                                Bundle bundle = new Bundle();
                                bundle.putParcelable(CITY, mLocation);
                                Intent intent = new Intent();
                                intent.putExtras(bundle);
                                getActivity().setResult(RESULT_OK, intent);
                                getActivity().finish();
                            }
                        }
                    });
                }
            }
            if (intent.getAction().equals(ForecastFragment.ACTION_LOCATION_START)) {
                location.setText("正在定位中...");
            }
            if (intent.getAction().equals(ForecastFragment.ACTION_LOCATION_FALSE)) {
                location.setText("定位失败");
            }
        }
    };

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getLoaderManager().initLoader(CITY_LOADER, null, this);
        //注册监听器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ForecastFragment.ACTION_LOCATION_START);
        intentFilter.addAction(ForecastFragment.ACTION_LOCATION_DONE);
        intentFilter.addAction(ForecastFragment.ACTION_LOCATION_FALSE);
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        localBroadcastManager.registerReceiver(mReceiver, intentFilter);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_select_city, null);
        Toolbar toolbar = (Toolbar) root.findViewById(R.id.awesome_toolbar);
        toolbar.setTitle("请选择城市信息");
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        mCityAdapter = new CityAdapter(getActivity(), null, false);
        mCityList = (ListView) root.findViewById(R.id.city_list_view);
        mCityList.setAdapter(mCityAdapter);
        mCityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int prePosition = mData.getPosition();
                if (mData.moveToPosition(position)) {
                    City city = new City(
                            mData.getString(mData.getColumnIndex(WeatherContract.CityEntry.COLUMN_NAME)),
                            mData.getDouble(mData.getColumnIndex(WeatherContract.CityEntry.COLUMN_LAT)),
                            mData.getDouble(mData.getColumnIndex(WeatherContract.CityEntry.COLUMN_LON))
                    );
                    //将用户选择的详细信息传递给主界面
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(CITY, city);
                    Intent intent = new Intent();
                    intent.putExtras(bundle);
                    getActivity().setResult(RESULT_OK, intent);
                    getActivity().finish();
                }
                mData.moveToPosition(prePosition);
            }
        });
        return root;
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始定位服务
        Intent intent = new Intent(getActivity(), LocationService.class);
        getActivity().startService(intent);

    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        switch (id) {
            case CITY_LOADER: {
                return new CursorLoader(getActivity(), WeatherContract.CITY_CONTENT_URI, null, null, null, WeatherContract.CityEntry.COLUMN_SORT + " asc");
            }
            default:
                return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        this.mData = data;
        //设置用于分组的AlphabetIndexer
        AlphabetIndexer indexer = new AlphabetIndexer(data, data.getColumnIndex(WeatherContract.CityEntry.COLUMN_SORT), mAlphabet);
        mCityAdapter.setmIndexer(indexer);
        mCityAdapter.swapCursor(data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消监听器
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        localBroadcastManager.unregisterReceiver(mReceiver);
    }


    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mCityAdapter.swapCursor(null);
    }
}
